package com.eckey.lab.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Marinc
 * @CreateTime: 2023-08-09  22:53
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class ExceptionHandler implements BlockExceptionHandler {

    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        String msg = "默认未知异常";
        Integer code = 1001;
        if (e instanceof FlowException) {
            msg = "限流异常";
            code = 1002;
        } else if (e instanceof ParamFlowException) {
            msg = "热点限流异常";
            code = 1003;
        } else if (e instanceof DegradeException) {
            msg = "降级异常";
            code = 1004;
        } else if (e instanceof AuthorityException) {
            msg = "授权异常";
            code = 1005;
        } else {
            msg = "系统异常";
            code = 1009;
        }
        httpServletResponse.setStatus(code);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().print("{"+"message:" + msg + ",code:" + code+"}");
    }
}
